package jdbc;

import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author oldliu
 * @since 1.0
 */
public class Transfer {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("转出账号：");
        String from=sc.next();
        System.out.println("转入账号：");
        String to=sc.next();
        System.out.println("转出金额：");
        int money=sc.nextInt();

        Connection con = DBUtil.getConnection();
        PreparedStatement p1=null,p2=null;
        String sql1="update bank set blance=blance-? where ac=?";
        String sql2="update bank set blance=blance+? where ac=?";
        try {
            con.setAutoCommit(false);
            p1=con.prepareStatement(sql1);
            p1.setInt(1,money);
            p1.setString(2,from);

            int r1=p1.executeUpdate();

            p2=con.prepareStatement(sql2);
            p2.setInt(1,money);
            p2.setString(2,to);
            int r2=p2.executeUpdate();
            System.out.println(r1+","+r2);
            if(r1==1 && r2==1){
                con.commit();
                System.out.println("Zhuan 账成功");
            }else
            {
                con.rollback();
                System.out.println("转账失败！");
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(p1);
            DBUtil.close(p2);
            DBUtil.close(con);
        }
    }
}
